package com.hub.grpc.server.config;


import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @ author 飞天蝙蝠
 * @ date & time 2024/12/30 15:36
 */
@Component
public class ServiceManager {

    private static final Logger log = LoggerFactory.getLogger(ServiceManager.class);
    private Server server;

    private int grpcServerPort = 9091;

    public void loadService(Map<String, Object> grpcServiceBeanMap) throws IOException, InterruptedException {
        if (grpcServiceBeanMap.isEmpty()) {
            log.warn("No grpc service bean found");
            return;
        }

        ServerBuilder serverBuilder = ServerBuilder.forPort(grpcServerPort);

        grpcServiceBeanMap.forEach((key, value) -> {
            serverBuilder.addService((BindableService) value);
            log.info("Load grpc service: {}", key);
        });

        server = serverBuilder.build().start();
        log.info("grpc server is started at :{}", server.getPort());

        // 增加一个钩子，当JVM进程退出时，Server 关闭
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("*** shutting down gRPC server since JVM is shutting down");
            if (server != null) {
                server.shutdown();
            }
            log.info("*** server shut down！！！！");
        }));

        server.awaitTermination();
    }
}
